#include "event_loop_thread_pool.h"
#include <functional>

EventLoopThread::EventLoopThread()
    : loop_(NULL),
      exiting_(false),
      mutex_(),
      cond_(mutex_)
{}

EventLoopThread::~EventLoopThread()
{
  exiting_ = true;
  if (loop_ != NULL)
  {
    loop_->Quit();
    thread_.join();
  }
}

EventLoop* EventLoopThread::startLoop()
{
  // assert(!thread_.started());
  // thread_.start();
  thread_ = std::thread(std::bind(&EventLoopThread::threadFunc, this));
  {
    MutexGuard lock(mutex_);
    while (loop_ == NULL)
      cond_.Wait();
  }
  return loop_;
}

void EventLoopThread::threadFunc()
{
  EventLoop loop;

  {
    MutexGuard lock(mutex_);
    loop_ = &loop;
    cond_.Signal();
  }

  loop.Loop();
  loop_ = NULL;
}